package com.zy.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.entity.SingleMessages;
import com.zy.chat.mapper.SingleMessageMapper;
import com.zy.chat.service.SaveSingleMessageService;
import com.zy.chat.vo.RequestParams;
import com.zy.chat.vo.Singlemsgs;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SaveSingleMessageServiceImpl extends ServiceImpl<SingleMessageMapper, SingleMessages> implements SaveSingleMessageService {

    @Autowired
    private SingleMessageMapper singleMessageMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public Singlemsgs search(RequestParams params) {
        //准备Request
        SearchRequest request = new SearchRequest("singlemsg");
        //准备请求参数
        buildBasicQuery(params,request);
        //发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return handleResponse(response);
    }


    @Override
    public List<SingleMessages> getNoRead(String username, String touser) {
        QueryWrapper<SingleMessages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_user",username).eq("to_user",touser).eq("status","未读");
        return singleMessageMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean updateToRead(String username, String touser) {
        UpdateWrapper<SingleMessages> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_user",username).eq("to_user",touser).set("STATUS","已读");
        int update = singleMessageMapper.update(null, updateWrapper);
        if(update!=0){
            return true;
        }
        return false;
    }

    private Singlemsgs handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        //总条数
        long total=searchHits.getTotalHits().value;
        //获取文档数组
        SearchHit[] hits = searchHits.getHits();
        //遍历
        ArrayList<SingleMessages> singleMessageslist = new ArrayList<>(hits.length);
        for(SearchHit hit:hits){
            //获取source
            String json=hit.getSourceAsString();
            //反序列化，非高亮的
            SingleMessages singleMessages = JSON.parseObject(json, SingleMessages.class);
            //处理高亮结果
            //获取高亮map
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2）根据字段名，获取高亮结果
                HighlightField highlightField = map.get("content");
                if (highlightField != null) {
                    // 3）获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4）把高亮结果放到HotelDoc中
                    singleMessages.setContent(hName);
                }
            }
            // 4.9.放入集合
            singleMessageslist.add(singleMessages);
        }
        return new Singlemsgs(total,singleMessageslist);
    }

    public void buildBasicQuery(RequestParams params, SearchRequest request){
        //准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //设置查询条件
        String username=params.getUsername();
        String touser=params.getTouser();
        boolQuery.filter(QueryBuilders.multiMatchQuery(username,"fromUser","toUser"));
        boolQuery.filter(QueryBuilders.multiMatchQuery(touser,"fromUser","toUser"));
        request.source().query(boolQuery);
        request.source().sort("sendTime", SortOrder.DESC).size(30);
        //关键字搜索
        String key=params.getKey();
        if(StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("content",key));
        }
    }


}
